package com.yeebo.common;

import com.yeebo.constants.Constants;
import com.yeebo.utils.RedisUtils;
import com.yeebo.utils.ResponseUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Admin Base Controller
 */
public class BaseController {

    @Resource
    private RedisUtils redisUtils;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        /**
         * 自动转换日期类型的字段格式
         */
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

    protected Object success(Object data) {
        return ResponseUtils.success(data);
    }

    protected Object error(Object data) {
        return ResponseUtils.error(data);
    }

    protected Long getUserId(HttpServletRequest request) {
        String userToken = request.getHeader(Constants.USER_TOKEN_HEADER_KEY);
        return Long.parseLong(redisUtils.get(Constants.TEMP_ADMIN_USER_ID_CACHE + userToken).toString());
    }

}
